#!/usr/bin/env python
#-*- coding: utf8 -*-

from dbcarta import *
from test.countries import *

def paint_dbcarta():
    for _i, name, short_name, _icon in tlist.getcurselection():
        data, i = [], 0
        icon = [None, icons.get(short_name)][check_legend_var.get()]
        legend = [None, name.encode('utf8')][check_legend_var.get()]
        for pcenter, poly in COUNTRIES[name][1]:
            data += [('Area', '%s.%s' % (short_name, i), poly, legend, pcenter, icon)]
            i += 1
        dbcarta.loadCarta(data, docenter=1)

def clear_dbcarta():
    for _i, name, short_name, _icon in tlist.getcurselection():
        for i in range(len(COUNTRIES[name][1])):
            dbcarta.clearCarta('Area.%s.%s' % (short_name, i))

def create_dbcarta(master, **kw):
    global dbcarta
    dbcarta = dbCarta(master, **kw)
    return dbcarta

def create_tlist(master):
    fmain = Frame(master)
    fmain.pack(fill='both', expand=1)
    fmain.columnconfigure(0, weight=1)
    fmain.rowconfigure(0, weight=1)
    global tlist
    tlist = TableList(fmain, 
        activestyle = 'none', 
        columns = (0, '#', 10, 'Страна', 0, 'Аббр.', 0, 'Флаг'),
        setfocus=1, 
        selectmode='extended', 
        selecttype='row', 
        stretch = 'all',
        width=50)
    tlist.grid(column=0, row=0, sticky='nsew')
    scroll_y = Scrollbar(fmain, orient='vertical', command=tlist.yview)
    scroll_y.grid(column=1, row=0, sticky='ns')
    tlist.config(yscrollcommand=scroll_y.set)
    
    global check_legend_var
    check_legend_var = IntVar()
    check_legend_var.set(1)
    check_legend = Checkbutton(fmain, text='Выводить с надписями', variable=check_legend_var)
    check_legend.grid(column=0,row=1)
    
    fbutt = Frame(fmain)
    fbutt.grid(column=0, row=2)
    btadd = Button(fbutt, text='Показать', command=paint_dbcarta)
    btadd.grid(column=0, row=0)
    btcls = Button(fbutt, text='Стереть', command=clear_dbcarta)
    btcls.grid(column=1, row=0)

def fill_tlist():
    """Заполняем список стран."""
    v = COUNTRIES.keys()
    v.sort()
    
    global icons
    icons = {}
    
    os.chdir(os.path.dirname(sys.argv[0]))
    for i, name in enumerate(v):
        short_name = COUNTRIES[name][0].lower()
        try:
            icons[short_name] = PhotoImage(file=os.path.join('test', 'flags', short_name + '.gif'))
        except:
            pass
        tlist.insert('end', tuple([i, name, short_name]))
        tlist.cellconfigure('%s,3' % (i,), image=icons.get(short_name))

if __name__ == '__main__':
    root = Tk()
    
    dbcarta = create_dbcarta(root)
    create_tlist(root)
    fill_tlist()
    
    root.mainloop()
